package com.shy.springframework.core.convert.converter;

import cn.hutool.core.lang.Assert;

import java.util.Set;

/**
 * @author yzpang
 * @desc: 通用转换接口
 * @date: 2023/2/14 16:40
 */
public interface GenericConverter {

    /**
     * 返回当前转换器能够转换的源与目标类型对集合
     * @return
     */
    Set<ConvertiblePair> getConvertibleTypes();

    /**
     * 根据传入的源与目标类型转换对象
     * @param source
     * @param sourceType
     * @param targetType
     * @return
     */
    Object convert(Object source, Class sourceType, Class targetType);



    final class ConvertiblePair{
        private final Class<?> sourceType;
        private final Class<?> targetType;

        public ConvertiblePair(Class<?> sourceType, Class<?> targetType) {
            Assert.notNull(sourceType, "Source type can not be null");
            Assert.notNull(targetType, "Target type can not be null");
            this.sourceType = sourceType;
            this.targetType = targetType;
        }

        public Class<?> getSourceType() {
            return sourceType;
        }

        public Class<?> getTargetType() {
            return targetType;
        }

        @Override
        public int hashCode() {
            return this.sourceType.hashCode() * 31 + this.targetType.hashCode();
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj){
                return true;
            }
            if (obj == null || obj.getClass() != ConvertiblePair.class){
                return false;
            }
            ConvertiblePair other = (ConvertiblePair) obj;
            return this.sourceType.equals(other.getSourceType()) && this.targetType.equals(other.getTargetType());
        }
    }
}
